// pages/msg/msg.js
import config from "../../config.js";
import utils from "../../utils/util.js";
const base = config;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0,
    // 我的管家
    manager: {},

    // 消息列表
    message: [],
    send: {
      content: '',
      from: null,
      to: null,
      image: null
    },
    chatUser: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var type = options.type;
    var user = wx.getStorageSync("chatUser");
    console.log(user);
    if (options.type == null || type == 1) {
      if (user != null) {
        this.setData({
          chatUser: user,
          'send.to': user.accountByAid,
        })

        var name = user.accountByAid.tel;
        if (user.accountByAid.name != null && user.accountByAid.name != "") {
          name = user.accountByAid.name;
        }

        wx.setNavigationBarTitle({
          title: '与' + name + "沟通中...",
        })
      }
    } else {
      if (type == 2) {
        var keeper = wx.getStorageSync("keeperAccount");
        wx.setNavigationBarTitle({
          title: '与' + keeper.housekeeper.name + "沟通中...",
        })
      }
    }




    user = wx.getStorageSync('user');
    if (user != null) {
      this.setData({
        'send.from': user,
      })
    }

    this.getCatMessageList();

  },
  getCatMessageList: function() {
    var that = this;
    var user = that.data.chatUser;
    console.log(user);
    var type = 1;
    var userId = -1;
    if (user != null) {
      userId = user.accountByAid.aid;
    }
    if (that.data.chatUser != null) {
      type = 0
    }

    //请求车辆列表
    wx.request({
      url: base.userChatMessageList,
      header: {
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        userId: userId,
        start: 0,
        size: 10,
        type: type
      },
      success: function(res) {
        console.log(res);
        if (res.data.status == 200) {
          var len = res.data.data.length //遍历的数组的长度
          that.setData({
            message: res.data.data,
            scrollTop: 1000 * len // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
          })


        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }

        if (res.data.keeperAccount != null) {
          that.setData({
            'send.to': res.data.keeperAccount,
          })

        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.addListener();
  },
  addListener: function() {
    var that = this;
    console.log("添加监听");
    app.globalData.callback = function (res) {
      console.log('收到服务器内容2：' + res.data)
      wx.setTabBarBadge({
        'index': 2,
        text: '1'
      })

      //解析消息 
      var json = JSON.parse(res.data);
      if (json.ntitle != null) {
        wx.showModal({
          title: json.ntitle,
          content: json.ncontent,
          success(e) {
            if (e.confirm) {
              if (json.isRead == "0") {
                wx.setStorageSync('orderConfirmType', 1);
                wx.setStorageSync('orderId', json.nid);
                wx.switchTab({
                  url: '../order/order',
                })
              } else {
                wx.setStorageSync('orderConfirmType', 1);
                wx.setStorageSync('orderId', json.nid);
                wx.navigateTo({
                  url: '../gjorder/gjorder',
                })
              }

            }
          }
        })
      } else {
        var msg = that.data.message;
        msg.push(json);
        that.setData({
          message: msg,
          scrollTop: 1000 * msg.length
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  sendInput: function(res) {
    console.log(res);
    var that = this;
    var content = res.detail.value;
    that.setData({
      'send.content': content
    })
  },
  blurAction: function(res) {
    var that = this;
    /** var content = res.detail.value;
     that.setData({
       'send.content': content
     })**/
  },
  sendAction: function(res) {
    var that = this;
    if (this.data.send.content != "") {
      console.log("进入!");
      console.log(this.data.send);


      if (this.data.send.from != null && this.data.send.to != null) {
        var pare = {};
        pare['from'] = this.data.send.from;
        pare['to'] = this.data.send.to;
        pare['content'] = this.data.send.content;
        pare['image'] = '';
        pare['type'] = "chat"
        pare['msgtype'] = 1
        console.log(pare);

        wx.sendSocketMessage({
          data: JSON.stringify(pare)
        })
        that.setData({
          'send.content': ""
        })

        //组织信息
        var sendMsg = {};
        sendMsg['accountByAid'] = this.data.send.from;
        sendMsg['accountByTaid'] = this.data.send.to;
        sendMsg['content'] = pare['content'];
        sendMsg['create'] = utils.getDateStr();
        sendMsg['from'] = "me";
        sendMsg['fromUserName'] = this.data.send.from.name;
        sendMsg['msgtype'] = {
          'typeId': 1
        };
        console.log("发送完成" + pare);

        var msgs = this.data.message;
        msgs.push(sendMsg);

        this.setData({
          message: msgs,
          scrollTop: 1000 * msgs.length
        })
      }
    }

  },
  chooesImg: function(res) {
    console.log(res);
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          'send.image': tempFilePaths,
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: base.uploadPic,
          folder: "chatMsg/",
          filePath: that.data.send.image[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                'send.image': res.fileName
              })

              that.addMsgContent(res.fileName);
            }
          }
        })
      },
    })
  },
  addMsgContent: function(res) {
    var that = this;
    if (this.data.send.from != null && this.data.send.to != null) {
      var pare = {};
      pare['from'] = this.data.send.from;
      pare['to'] = this.data.send.to;
      pare['content'] = this.data.send.content;
      pare['image'] = res;
      pare['type'] = "chat"
      pare['msgtype'] = 2
      console.log(pare);

      wx.sendSocketMessage({
        data: JSON.stringify(pare)
      })
      console.log("发送完成" + pare);
      this.setData({
        'send.content': ""
      })

      //组织信息
      var sendMsg = {};
      sendMsg['accountByAid'] = this.data.send.from;
      sendMsg['accountByTaid'] = this.data.send.to;
      sendMsg['content'] = '';
      sendMsg['create'] = utils.getDateStr();
      sendMsg['from'] = "me";
      sendMsg['picUrl'] = res;
      sendMsg['fromUserName'] = this.data.send.from.name;
      sendMsg['msgtype'] = {
        'typeId': 2
      };
      console.log("发送完成" + pare);

      var msgs = this.data.message;
      msgs.push(sendMsg);

      this.setData({
        message: msgs,
        scrollTop: 1000 * msgs.length
      })

    }

  },
  previewImg: function(e) {
    console.log(e.currentTarget.dataset.url);
    var url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, //当前图片地址 
      urls: [url], //所有要预览的图片的地址集合 数组形式 
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  }
})